package com.google.code.mergeinformer.constraint.impl;

import com.google.code.mergeinformer.constraint.Reachable;
import com.google.code.mergeinformer.model.VcsAttributes;
import com.google.code.mergeinformer.model.VcsAttributesCheckResult;
import com.google.code.mergeinformer.service.VcsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author Dmitry Golubev
 */
@Configurable
public class ReachableValidator implements ConstraintValidator<Reachable, VcsAttributes> {

    private static final Logger log = LoggerFactory.getLogger(ReachableValidator.class);

    @Autowired
    private VcsService vcsService;

    @Override
    public void initialize(Reachable constraintAnnotation) {
    }

    @Override
    public boolean isValid(VcsAttributes value, ConstraintValidatorContext context) {
        switch (vcsService.checkAttributes(value)) {
            case OK:
                return true;
            case INVALID_URL_FORMAT:
                setMessage(context, "URL is invalid");
                break;
            case AUTHENTICATION_FAILURE:
                setMessage(context, "Authentication failure");
                break;
            case NON_EXISTENT_ENTRY:
                    setMessage(context, "URL is non-existent in the repository");
                break;
            case UNREACHABLE_URL:
                setMessage(context, "URL is unreachable");
                break;
            default:
                log.error("Unexpected value of " + VcsAttributesCheckResult.class + " inside switch statement");
                setMessage(context, "URL is not valid");
                return false;
        }
        return false;
    }

    private void setMessage(ConstraintValidatorContext context, String message) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
    }
}
